package io.finer.erp.jeecg.stock.controller;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import io.finer.erp.jeecg.stock.vo.StkPickUpBillVo;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import io.finer.erp.jeecg.bas.entity.BasMaterialCategory;
import io.finer.erp.jeecg.bas.entity.ZrkOrderProcess;
import io.finer.erp.jeecg.bas.service.IBasMaterialCategoryService;
import io.finer.erp.jeecg.stock.entity.StkPickUpBill;
import io.finer.erp.jeecg.stock.entity.StkPickUpEntry;
import io.finer.erp.jeecg.stock.service.IStkPickUpBillService;
import io.finer.erp.jeecg.stock.service.IStkPickUpEntryService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

 /**
 * @Description: 提货单
 * @Author: jeecg-boot
 * @Date:   2020-11-10
 * @Version: V1.0
 */
@Api(tags="提货单")
@RestController
@RequestMapping("/stock/stkPickUpBill")
@Slf4j
public class StkPickUpBillController extends JeecgController<StkPickUpBill, IStkPickUpBillService> {

	@Autowired
	private IStkPickUpBillService stkPickUpBillService;

	@Autowired
	private IStkPickUpEntryService stkPickUpEntryService;
	
	@Autowired
	private IBasMaterialCategoryService categoryService;


	/*---------------------------------主表处理-begin-------------------------------------*/

	/**
	 * 分页列表查询
	 * @param stkPickUpBill
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "提货单-分页列表查询")
	@ApiOperation(value="提货单-分页列表查询", notes="提货单-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(StkPickUpBill stkPickUpBill,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		String billNo =req.getParameter("billNo");
		String mesId =req.getParameter("mesId");
		String deviceId =req.getParameter("deviceId");
		String billStatus =req.getParameter("billStatus");
		String isPush =req.getParameter("isPush");
//		QueryWrapper<StkPickUpBill> queryWrapper = QueryGenerator.initQueryWrapper(stkPickUpBill, req.getParameterMap());
		Page<StkPickUpBillVo> page = new Page<StkPickUpBillVo>(pageNo, pageSize);
//		IPage<StkPickUpBill> pageList = stkPickUpBillService.page(page, queryWrapper);
		IPage<StkPickUpBillVo> pageList=stkPickUpBillService.selectUpBill(page,billNo,mesId,deviceId,billStatus,isPush);
		return Result.ok(pageList);
	}

	/**
     *   添加
     * @param stkPickUpBill
     * @return
     */
    @AutoLog(value = "提货单-添加")
    @ApiOperation(value="提货单-添加", notes="提货单-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody StkPickUpBill stkPickUpBill) {
        stkPickUpBillService.save(stkPickUpBill);
        return Result.ok("添加成功！");
    }

    /**
     *  编辑
     * @param stkPickUpBill
     * @return
     */
    @AutoLog(value = "提货单-编辑")
    @ApiOperation(value="提货单-编辑", notes="提货单-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody StkPickUpBill stkPickUpBill) {
        stkPickUpBillService.updateById(stkPickUpBill);
        return Result.ok("编辑成功!");
    }

    /**
     * 通过id删除
     * @param id
     * @return
     */
    @AutoLog(value = "提货单-通过id删除")
    @ApiOperation(value="提货单-通过id删除", notes="提货单-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name="id",required=true) String id) {
        stkPickUpBillService.delMain(id);
        return Result.ok("删除成功!");
    }

    /**
     * 批量删除
     * @param ids
     * @return
     */
    @AutoLog(value = "提货单-批量删除")
    @ApiOperation(value="提货单-批量删除", notes="提货单-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
        this.stkPickUpBillService.delBatchMain(Arrays.asList(ids.split(",")));
        return Result.ok("批量删除成功!");
    }

    /**
     * 导出
     * @return
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, StkPickUpBill stkPickUpBill) {
        return super.exportXls(request, stkPickUpBill, StkPickUpBill.class, "提货单");
    }

    /**
     * 导入
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, StkPickUpBill.class);
    }
	/*---------------------------------主表处理-end-------------------------------------*/
	

    /*--------------------------------子表处理-提货单详情-begin----------------------------------------------*/
	/**
	 * 通过主表ID查询
	 * @return
	 */
	@AutoLog(value = "提货单详情-通过主表ID查询")
	@ApiOperation(value="提货单详情-通过主表ID查询", notes="提货单详情-通过主表ID查询")
	@GetMapping(value = "/listStkPickUpEntryByMainId")
    public Result<?> listStkPickUpEntryByMainId(StkPickUpEntry stkPickUpEntry,
                                                    @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                    @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                    HttpServletRequest req) {
        QueryWrapper<StkPickUpEntry> queryWrapper = QueryGenerator.initQueryWrapper(stkPickUpEntry, req.getParameterMap());
        Page<StkPickUpEntry> page = new Page<StkPickUpEntry>(pageNo, pageSize);
        IPage<StkPickUpEntry> pageList = stkPickUpEntryService.page(page, queryWrapper);
        List<StkPickUpEntry> list = pageList.getRecords();
        if(null != list && 0 != list.size()) {
        	for (StkPickUpEntry entry : list) {
				String categoryId = entry.getCategoryId();
				if(StringUtils.isNotBlank(categoryId)) {
					BasMaterialCategory category = this.categoryService.getById(categoryId);
					if(null != category) {
						entry.setCategoryName(category.getName());
					}
				}
			}
        }
        return Result.ok(pageList);
    }

	/**
	 * 添加
	 * @param stkPickUpEntry
	 * @return
	 */
	@AutoLog(value = "提货单详情-添加")
	@ApiOperation(value="提货单详情-添加", notes="提货单详情-添加")
	@PostMapping(value = "/addStkPickUpEntry")
	public Result<?> addStkPickUpEntry(@RequestBody StkPickUpEntry stkPickUpEntry) {
		String categoryId = stkPickUpEntry.getMaterialId();
		BasMaterialCategory category = this.categoryService.getById(categoryId);
		if(null != category) {
			stkPickUpEntry.setMaterialCode(category.getCode());
		}
		stkPickUpEntryService.save(stkPickUpEntry);
		return Result.ok("添加成功！");
	}

    /**
	 * 编辑
	 * @param stkPickUpEntry
	 * @return
	 */
	@AutoLog(value = "提货单详情-编辑")
	@ApiOperation(value="提货单详情-编辑", notes="提货单详情-编辑")
	@PutMapping(value = "/editStkPickUpEntry")
	public Result<?> editStkPickUpEntry(@RequestBody StkPickUpEntry stkPickUpEntry) {
		stkPickUpEntryService.updateById(stkPickUpEntry);
		return Result.ok("编辑成功!");
	}

	/**
	 * 通过id删除
	 * @param id
	 * @return
	 */
	@AutoLog(value = "提货单详情-通过id删除")
	@ApiOperation(value="提货单详情-通过id删除", notes="提货单详情-通过id删除")
	@DeleteMapping(value = "/deleteStkPickUpEntry")
	public Result<?> deleteStkPickUpEntry(@RequestParam(name="id",required=true) String id) {
		stkPickUpEntryService.removeById(id);
		return Result.ok("删除成功!");
	}

	/**
	 * 批量删除
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "提货单详情-批量删除")
	@ApiOperation(value="提货单详情-批量删除", notes="提货单详情-批量删除")
	@DeleteMapping(value = "/deleteBatchStkPickUpEntry")
	public Result<?> deleteBatchStkPickUpEntry(@RequestParam(name="ids",required=true) String ids) {
	    this.stkPickUpEntryService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.ok("批量删除成功!");
	}

    /**
     * 导出
     * @return
     */
    @RequestMapping(value = "/exportStkPickUpEntry")
    public ModelAndView exportStkPickUpEntry(HttpServletRequest request, StkPickUpEntry stkPickUpEntry) {
		 // Step.1 组装查询条件
		 QueryWrapper<StkPickUpEntry> queryWrapper = QueryGenerator.initQueryWrapper(stkPickUpEntry, request.getParameterMap());
		 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

		 // Step.2 获取导出数据
		 List<StkPickUpEntry> pageList = stkPickUpEntryService.list(queryWrapper);
		 List<StkPickUpEntry> exportList = null;

		 // 过滤选中数据
		 String selections = request.getParameter("selections");
		 if (oConvertUtils.isNotEmpty(selections)) {
			 List<String> selectionList = Arrays.asList(selections.split(","));
			 exportList = pageList.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
		 } else {
			 exportList = pageList;
		 }

		 // Step.3 AutoPoi 导出Excel
		 ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
		 mv.addObject(NormalExcelConstants.FILE_NAME, "提货单详情"); //此处设置的filename无效 ,前端会重更新设置一下
		 mv.addObject(NormalExcelConstants.CLASS, StkPickUpEntry.class);
		 mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("提货单详情报表", "导出人:" + sysUser.getRealname(), "提货单详情"));
		 mv.addObject(NormalExcelConstants.DATA_LIST, exportList);
		 return mv;
    }

    /**
     * 导入
     * @return
     */
    @RequestMapping(value = "/importStkPickUpEntry/{mainId}")
    public Result<?> importStkPickUpEntry(HttpServletRequest request, HttpServletResponse response, @PathVariable("mainId") String mainId) {
		 MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		 Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		 for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
			 MultipartFile file = entity.getValue();// 获取上传文件对象
			 ImportParams params = new ImportParams();
			 params.setTitleRows(2);
			 params.setHeadRows(1);
			 params.setNeedSave(true);
			 try {
				 List<StkPickUpEntry> list = ExcelImportUtil.importExcel(file.getInputStream(), StkPickUpEntry.class, params);
				 for (StkPickUpEntry temp : list) {
                    temp.setBillId(mainId);
				 }
				 long start = System.currentTimeMillis();
				 stkPickUpEntryService.saveBatch(list);
				 log.info("消耗时间" + (System.currentTimeMillis() - start) + "毫秒");
				 return Result.ok("文件导入成功！数据行数：" + list.size());
			 } catch (Exception e) {
				 log.error(e.getMessage(), e);
				 return Result.error("文件导入失败:" + e.getMessage());
			 } finally {
				 try {
					 file.getInputStream().close();
				 } catch (IOException e) {
					 e.printStackTrace();
				 }
			 }
		 }
		 return Result.error("文件导入失败！");
    }
    
    /**
     * @Description 生产订单工序处发过来的请求，新增一条提货单信息。
     * @param process
     * @return
     * Create at: 2020-11-10 14:29:00
     * @author: duany
     * Revision:
     *    2020-11-10 14:29:00 - first revision by duany
     *        
     */
    @PostMapping("addPickUp")
    public Result<?> addPickUp(@RequestBody ZrkOrderProcess process){
    	String id = process.getId();
    	return this.stkPickUpBillService.addPickUp(id);
    }

    /*--------------------------------子表处理-提货单详情-end----------------------------------------------*/
    @GetMapping("/addPicupEntry")
    public Result<?> addPicupEntry(@RequestParam(name = "materialId")String materialId,
    		@RequestParam(name = "ids")String ids){
    	return this.stkPickUpBillService.addPicupEntry(materialId, ids);
    }

    @GetMapping("/getCutting")
    public Result<?> getCutting(@RequestParam(name = "id", required = false)String id){
    	if(!StringUtils.isBlank(id)) {
    		id = id.replace(",", "");
    	}
    	return stkPickUpBillService.getCutting(id);
    }
}
